;
(function () {
  'use strict';
  angular.module('services.timeDataDis', [])
    .service('totalTransactionModel', totalTransactionModel)
    .service('healthModel', healthModel)
    .service('timeDataDisModel', timeDataDisModel)
    .service('sysPerformanceModel', sysPerformanceModel)
    .service('provinceSuccessRateOfTransModel', provinceSuccessRateOfTransModel)
    .service('timeDataDisSuccessRateModel', timeDataDisSuccessRateModel)
    .service('provinceVolumeOfBusModel', provinceVolumeOfBusModel)
    .service('timeDataDisVolumeOfBusModel', timeDataDisVolumeOfBusModel)
    .factory('timeDataDisServer', ['Restangular', timeDataDisServer])
    .factory('socketServer', ['COREDATA', socketServer])
    .factory('provinceChartServer', [provinceChartServer])
    .factory('totalTransactionServer', ['timeDataDisServer', 'socketServer', 'totalTransactionModel', '$rootScope', totalTransactionServer])
    .factory('topUpPreferServer', ['timeDataDisServer', 'socketServer', 'timeDataDisModel', topUpPreferServer])
    .factory('splitTimeServer', ['timeDataDisServer', 'socketServer', 'timeDataDisVolumeOfBusModel', '$state', splitTimeServer])
    .factory('sysPerformanceServer', ['timeDataDisServer', 'socketServer', 'sysPerformanceModel', '$rootScope', sysPerformanceServer])
    .factory('healthServer', ['timeDataDisServer', 'socketServer', 'healthModel', '$rootScope', healthServer])
    .factory('provinceSuccessRateOfTransServer', ['timeDataDisServer', 'socketServer', 'provinceChartServer', 'provinceSuccessRateOfTransModel', '$rootScope', '$state', provinceSuccessRateOfTransServer])
    .factory('provinceVolumeOfBusServer', ['timeDataDisServer', 'socketServer', 'provinceChartServer', 'provinceVolumeOfBusModel', '$rootScope', '$state', provinceVolumeOfBusServer])
    .factory('timeDataDisSuccessRateServer', ['timeDataDisServer', 'socketServer', 'timeDataDisSuccessRateModel', '$state', timeDataDisSuccessRateServer]);

  function timeDataDisModel() {

    this.sysList = [
      {
        title: '天猫旗舰店',
        unit: ''
      },
      {
        title: '移动商城',
        unit: ''
      },
      {
        title: '银行总对总',
        unit: ''
      },
      {
        title: '有价卡',
        unit: ''
      },
      {
        title: '灵犀语音',
        unit: ''
      }
    ];
  }

  function timeDataDisSuccessRateModel() {
    this.loding = true;
  }

  function timeDataDisVolumeOfBusModel() {
    this.loding = true;
  }

  function provinceVolumeOfBusModel() {
    this.loding = true;
    this.volState = 2;
    this.top = [];
    this.bottom = [];
  }

  function provinceSuccessRateOfTransModel() {
    this.rateState = 2;
    this.top = [];
    this.bottom = [];
  }

  function totalTransactionModel() {
    this.loding = true;
    this.total = {};
    this.list = [];
  }

  function healthModel() {
    this.loding = true;
    this.sumHealth = '';
    this.sumHealthState = '';
  }

  function sysPerformanceModel() {
    this.loding = true;
    this.processTime = '';
    this.throughput = '';
    this.tps = '';
  }

  function topUpPreferServer(timeDataDisServer, socketServer, timeDataDisModel) {

    var option = {
      tooltip: {
        trigger: 'axis',
        formatter: '订单金额（元）: {b}<br/>交易量（万笔）: {c}'
      },
      legend: {
        show: false,
        data: []
      },
      grid: {
        borderWidth: 0,
        y: '12%',
        height: '70%'
      },
      toolbox: {
        show: false
      },
      xAxis: [
        {
          type: 'value',
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          }
        }
      ],
      yAxis: [
        {
          type: 'category',
          data: [],
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisLabel: {show: true, interval: 0, textStyle: {baseline: "middle"}}
        }
      ],
      series: [
        {
          clickable: false,
          type: 'bar',
          data: []
        }
      ]
    };

    var chartList = [];
    var optionList = [];
    var sysList = [];

    function initChart(option, element, result, idx) {
      if (result.flag[0] === '1') {
        timeDataDisModel.sysList[idx].unit = '万笔';
        option.tooltip.formatter = '订单金额（元）: {b}<br/>交易量（万笔）: {c}';
      } else {
        timeDataDisModel.sysList[idx].unit = '笔';
        option.tooltip.formatter = '订单金额（元）: {b}<br/>交易量（笔）: {c}';
      }
      option.yAxis[0].data = result.rechargeAmount;
      option.series[0].data = result.volumeOfTrans;
      element.setOption(option);
    }

    function onSocket() {
      socketServer.socket.on('topUpPrefer', function (result) {
        try {
          angular.forEach(sysList, function (sys, idx) {
            initChart(optionList[idx], chartList[idx], result[sys], idx);
          });
        } catch (e) {
          alert(e.name + ": " + e.message);
        }
      });
    }

    return {
      initTopUpPrefer: function (id, sys) {
        chartList = [];
        optionList = [];
        sysList = sys;
        angular.forEach(sysList, function (sys, idx) {
          chartList.push(echarts.init(document.getElementById(id + idx)));
          optionList.push(angular.copy(option));
        });
        timeDataDisServer.queryTopUpPrefer(function (result) {
          if (result.state === '10000') {
            angular.forEach(sysList, function (sys, idx) {
              initChart(optionList[idx], chartList[idx], result.data[sys], idx);
            });
            onSocket();
          }
        });
      }
    };
  }

  function splitTimeServer(timeDataDisServer, socketServer, timeDataDisVolumeOfBusModel, $state) {

    var option = {
      tooltip: {
        trigger: 'axis'
      },
      toolbox: {},
      legend: {
        show: false,
        data: []
      },
      grid: {
        borderWidth: 0,
        y: '12%',
        height: '70%'
      },
      xAxis: [
        {
          type: 'category',
          data: '',
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisLabel: {
            interval: 2
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '交易金额(万元)',
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          }
        },
        {
          type: 'value',
          name: '交易量(笔)',
          splitArea: {
            show: false
          },
          splitLine: {
            show: false
          }
        }
      ],
      series: [
        {
          name: '交易量(笔)',
          type: 'bar',
          yAxisIndex: 1,
          clickable: true,
          data: ''
        },
        {
          name: '交易金额(万元)',
          type: 'line',
          clickable: true,
          data: ''
        }
      ]
    };

    var chartList = [];
    var optionList = [];
    var sysList = [];

    function setSplitTimeChart(option, element, data, sys) {

      if (sys === 'tmall') {
        option.series[1].name = '交易金额(万元)';
        option.yAxis[0].name = '交易金额(万元)';
      } else {
        option.series[1].name = '交易金额(元)';
        option.yAxis[0].name = '交易金额(元)';
      }

      element.addData([
        [
          0,        // 系列索引
          data.volumeOfBus, // 新增数据
          false,     // 新增数据是否从队列头部插入
          false     // 是否增加队列长度，false则自定删除原有数据，队头插入删队尾，队尾插入删队头
        ],
        [
          1,        // 系列索引
          data.trancAmount, // 新增数据
          false,    // 新增数据是否从队列头部插入
          false,    // 是否增加队列长度，false则自定删除原有数据，队头插入删队尾，队尾插入删队头
          data.volumeTime  // 坐标轴标签
        ]
      ]);
    }

    function initSplitTimeChart(option, element, data, sys) {

      if (sys === 'tmall') {
        option.series[1].name = '交易金额(万元)';
        option.yAxis[0].name = '交易金额(万元)';
      } else {
        option.series[1].name = '交易金额(元)';
        option.yAxis[0].name = '交易金额(元)';
      }

      option.xAxis[0].data = data.volumeTime;
      option.series[1].data = data.trancAmount;
      option.series[0].data = data.volumeOfBus;

      if (option.xAxis[0].data.length < 24) {

        for (var i = 0, j = 24 - option.xAxis[0].data.length; i < j; i++) {
          option.xAxis[0].data.unshift('');
          option.series[1].data.unshift(0);
          option.series[0].data.unshift(0);
        }
      }
      element.setOption(option);
    };

    function initChart() {
      timeDataDisVolumeOfBusModel.loding = true;
      timeDataDisServer.queryVolumeOfBus(function (result) {
        timeDataDisVolumeOfBusModel.loding = false;
        if (result.state === '10000') {
          angular.forEach(sysList, function (sys, idx) {
            initSplitTimeChart(optionList[idx], chartList[idx], result.data[sys], sys);
          });
          onSocket();
        }
      });
    }

    function onSocket() {
      socketServer.socket.on('volumeOfBus', function (result) {
        try {
          angular.forEach(sysList, function (sys, idx) {
            setSplitTimeChart(optionList[idx], chartList[idx], result[sys], sys);
          });
          //console.log('socket volumeOfBus...');
        } catch (e) {
          alert(e.name + ": " + e.message);
        }
      });
    }

    return {

      initSplitTime: function (id, sys) {
        chartList = [];
        optionList = [];
        sysList = sys;
        angular.forEach(sysList, function (sys, idx) {
          var temp = echarts.init(document.getElementById(id + idx));
          temp.on(echarts.config.EVENT.CLICK, function () {
            $state.go('sas.omdisplay.sysBusinessStatistics.sumStatistics');
          });
          chartList.push(temp);
          optionList.push(angular.copy(option));
        });
        initChart();
      }
    };
  }

  function totalTransactionServer(timeDataDisServer, socketServer, totalTransactionModel, $rootScope) {

    return {

      initTotalTransaction: function () {
        totalTransactionModel.loding = true;
        timeDataDisServer.querySysTransaction(function (result) {
          totalTransactionModel.loding = false;
          if ('10000' === result.state) {
            totalTransactionModel.total = result.data.shift();
            totalTransactionModel.list = result.data;
            socketServer.socket.on('sysTransaction', function (d) {
              try {
                totalTransactionModel.total = d.shift();
                totalTransactionModel.list = d;
                $rootScope.$digest();
                //console.log('socket sysTransaction...');
              } catch (e) {
                alert(e.name + ": " + e.message);
              }
            });
          }
        });
      }
    };
  }

  function sysPerformanceServer(timeDataDisServer, socketServer, sysPerformanceModel, $rootScope) {

    return {
      initSysPerformance: function () {
        sysPerformanceModel.loding = true;
        timeDataDisServer.querySysPerformance(function (result) {
          sysPerformanceModel.loding = false;
          if ('10000' === result.state) {
            sysPerformanceModel.processTime = result.data.processTime || 0;
            sysPerformanceModel.throughput = result.data.throughput || 0;
            sysPerformanceModel.tps = result.data.tps || 0;
            socketServer.socket.on('sysPerformance', function (result) {
              try {
                sysPerformanceModel.processTime = result.processTime || 0;
                sysPerformanceModel.throughput = result.throughput || 0;
                sysPerformanceModel.tps = result.tps || 0;
                $rootScope.$digest();
                //console.log('socket sysPerformance...');
              } catch (e) {
                alert(e.name + ": " + e.message);
              }
            });
          }
        });
      }
    };
  }

  function socketServer(COREDATA) {
    try {
      var socket = io.connect('http://' + COREDATA.SOCKETIP);
      //console.log('socket listener...');
    } catch (e) {
      alert(e.name + ": " + e.message);
    }
    socket.on('error', function () {
      //console.log('cocket error...');
    });
    socket.on('disconnected', function () {
      //console.log('cocket disconnected...');
    });
    socket.on('reconnect', function () {
      //console.log('cocket reconnect...');
    });
    return {
      socket: socket
    };
  }

  function provinceVolumeOfBusServer(timeDataDisServer, socketServer, provinceChartServer, provinceVolumeOfBusModel, $rootScope, $state) {

    var element = null;

    function initChart(option, element, result) {
      provinceVolumeOfBusModel.rateState = result.rateState;
      provinceVolumeOfBusModel.top = result.max;
      provinceVolumeOfBusModel.bottom = result.min;
      var normal = [];
      var abnormal = [];
      angular.forEach(result.provinceData, function (obj) {
        obj.value = obj.volume;
        obj.name = obj.provinceName;
        if (obj.volState === 1) {
          abnormal.push(obj);
        } else {
          normal.push(obj);
        }
      });
      option.tooltip.formatter = function (params) {
        if (params[2] === '-') {
          return '暂不统计';
        }
        return params[1] + '<br/>' + params[2] + '笔';
      };
      option.series[1].data = abnormal;
      option.series[2].data = normal;
      element.setOption(option);
    }

    function onSocket(option, element) {

      socketServer.socket.on('provinceVolumeOfBus', function (result) {
        try {
          initChart(option, element, result);
          $rootScope.$digest();
          //console.log('socket provinceVolumeOfBus...');
        } catch (e) {
          alert(e.name + ": " + e.message);
        }
      });
    }

    return {

      initProvinceVolumeOfBus: function (id) {
        timeDataDisServer.queryProvinceVolumeOfBus(function (result) {
          element = echarts.init(document.getElementById(id));
          element.on(echarts.config.EVENT.CLICK, function () {
            $state.go('sas.omdisplay.sysBusinessStatistics.sumStatistics');
          });
          if ('10000' === result.state) {
            initChart(provinceChartServer.option, element, result.data);
            onSocket(provinceChartServer.option, element);
          }
        });
      }
    };
  }

  function provinceSuccessRateOfTransServer(timeDataDisServer, socketServer, provinceChartServer, provinceSuccessRateOfTransModel, $rootScope, $state) {

    var element = null;

    function initChart(option, element, result) {
      provinceSuccessRateOfTransModel.volState = result.volState;
      provinceSuccessRateOfTransModel.top = result.max;
      provinceSuccessRateOfTransModel.bottom = result.min;
      var normal = [];
      var abnormal = [];
      angular.forEach(result.provinceData, function (obj) {
        obj.value = obj.rate;
        obj.name = obj.provinceName;
        if (obj.rateState === 1) {
          abnormal.push(obj);
        } else {
          normal.push(obj);
        }
      });
      option.tooltip.formatter = function (params) {
        if (params[2] === '-') {
          return '暂不统计';
        }
        params[2] = parseFloat(params[2]).toFixed(2);
        return params[1] + '<br/>' + params[2] + '%';
      };
      option.series[1].data = abnormal;
      option.series[2].data = normal;
      element.setOption(option, true);
    }

    function onSocket(option, element) {

      socketServer.socket.on('provinceSuccessRateOfTrans', function (result) {
        try {
          initChart(option, element, result);
          $rootScope.$digest();
          //console.log('socket provinceSuccessRateOfTrans...');
        } catch (e) {
          alert(e.name + ": " + e.message);
        }
      });
    }

    return {

      initProvinceSuccessRateOfTrans: function (id) {
        provinceSuccessRateOfTransModel.loding = true;
        timeDataDisServer.queryProvinceSuccessRateOfTrans(function (result) {
          provinceSuccessRateOfTransModel.loding = false;
          element = echarts.init(document.getElementById(id));
          element.on(echarts.config.EVENT.CLICK, function () {
            $state.go('sas.omdisplay.success.successRate');
          });
          if ('10000' === result.state) {
            initChart(provinceChartServer.option, element, result.data);
            onSocket(provinceChartServer.option, element);
          }
        });
      }
    };
  }

  function provinceChartServer() {

    var option = {
      title: {
        show: false
      },
      tooltip: {
        trigger: 'item',
        formatter: ''
      },
      legend: {
        show: false,
        data: []
      },
      toolbox: {
        show: false
      },
      series: [
        {
          name: '',
          type: 'map',
          mapType: 'china',
          itemStyle: {
            normal: {color: '#2196f3', borderColor: '#fff', borderWidth: '.7', label: {show: true}}
          },
          clickable: true,
          mapLocation: {y: 'top', height: 300},
          data: []
        },
        {
          name: '告警省市',
          type: 'map',
          mapType: 'china',
          clickable: true,
          itemStyle: {
            normal: {color: '#f44336', borderColor: '#fff', borderWidth: '.7', label: {show: true}}
          },
          mapLocation: {y: 'top', height: 300},
          data: []
        },
        {
          name: '正常省市',
          type: 'map',
          mapType: 'china',
          clickable: true,
          itemStyle: {
            normal: {color: '#2196f3', borderColor: '#fff', borderWidth: '.7', label: {show: true}}
          },
          mapLocation: {y: '60', height: 400},
          data: []
        }
      ]
    };

    return {

      option: option
    };
  }

  function timeDataDisSuccessRateServer(timeDataDisServer, socketServer, timeDataDisSuccessRateModel, $state) {

    var busChart = null;
    var sysChart = null;

    //业务处理成功率图表
    var option = {
      series: [
        {
          type: 'pie',
          center: ['50%', '50%'],
          radius: ['62%', '92%'],
          clickable: true,
          x: '0%',
          itemStyle: {
            emphasis: {
              color: 'rgba(0,0,0,0)'
            },
            normal: {
              label: {
                formatter: function (params) {
                  return params.value + '%';
                },
                textStyle: {
                  baseline: 'middle',
                  color: '#333',
                  fontSize: 16
                }
              }
            }
          },
          data: [
            {
              itemStyle: {
                normal: {
                  label: {
                    show: true,
                    position: 'center'
                  },
                  labelLine: {
                    show: false
                  }
                }
              }
            }, {
              itemStyle: {
                normal: {
                  color: '#ccc',
                  label: {
                    show: false,
                  },
                  labelLine: {
                    show: false
                  }
                }
              }
            }
          ]
        }
      ]
    };

    function initChart(option, busChart, sysChart, data) {
      if (data.successRateOfBusState === 1) {
        option.series[0].data[0].itemStyle.normal.color = '#f44336';
      } else {
        option.series[0].data[0].itemStyle.normal.color = '#4caf50';
      }
      option.series[0].data[0].value = parseFloat(data.successRateOfBus.toFixed(2));
      option.series[0].data[1].value = 100 - option.series[0].data[0].value;
      busChart.setOption(option);

      if (data.successRateOfSysState === 1) {
        option.series[0].data[0].itemStyle.normal.color = '#f44336';
      } else {
        option.series[0].data[0].itemStyle.normal.color = '#4caf50';
      }
      option.series[0].data[0].value = parseFloat(data.successRateOfSys.toFixed(2));
      option.series[0].data[1].value = 100 - option.series[0].data[0].value;
      sysChart.setOption(option);
    }

    function onSocket(option, busChart, sysChart) {
      socketServer.socket.on('successRate', function (result) {
        try {
          initChart(option, busChart, sysChart, result);
          //console.log('socket successRate...');
        } catch (e) {
          alert(e.name + ": " + e.message);
        }
      });
    }

    return {

      initSuccessRate: function (busId, sysId) {
        timeDataDisSuccessRateModel.loding = true;
        timeDataDisServer.querySuccessRate(function (result) {
          timeDataDisSuccessRateModel.loding = false;
          if ('10000' === result.state) {
            busChart = echarts.init(document.getElementById(busId));
            sysChart = echarts.init(document.getElementById(sysId));

            busChart.on(echarts.config.EVENT.CLICK, function () {
              $state.go('sas.omdisplay.success.successRate');
            });

            sysChart.on(echarts.config.EVENT.CLICK, function () {
              $state.go('sas.omdisplay.success.successRate');
            });

            initChart(option, busChart, sysChart, result.data);
            onSocket(option, busChart, sysChart);
          }
        });
      }
    };
  }

  function healthServer(timeDataDisServer, socketServer, healthModel, $rootScope) {

    var chart = null;

    var item = {
      value: 20,
      name: '',
      itemStyle: {
        normal: {
          label: {textStyle: {color: '#607d8b', fontSize: 16}},
          borderWidth: '2',
          borderColor: "#fff",
          labelLine: {lineStyle: {color: '#607d8b'}},
          color: '#4caf50'
        },
        emphasis: {
          borderWidth: '2',
          borderColor: "#fff",
          color: 'transparent'
        }
      }
    };

    var option = {
      tooltip: {
        show: false
      },
      legend: {
        data: [],
        show: false
      },
      toolbox: {
        show: false
      },
      series: [
        {
          type: 'pie',
          radius: ['50%', '72%'],
          center: ['50%', '46%'],
          clickable: false,
          data: [angular.copy(item), angular.copy(item), angular.copy(item), angular.copy(item), angular.copy(item)]
        }
      ]
    };

    function getColorByKey(key) {
      key = parseInt(key);
      switch (key) {
        case 1:
        {
          return '#4caf50';
        }
        case 2:
        {
          return '#2196f3';
        }
        case 3:
        {
          return '#ffeb3b';
        }
        case 4:
        {
          return '#f44336';
        }
        default :
        {
          return '#4caf50';
        }
      }
    }

    function getLevelByKey(key) {
      key = parseInt(key);
      switch (key) {
        case 1:
        {
          return '优';
        }
        case 2:
        {
          return '良';
        }
        case 3:
        {
          return '中';
        }
        case 4:
        {
          return '差';
        }
        default :
        {
          return '优';
        }
      }
    }

    function initChart(option, chart, result) {

      healthModel.sumHealth = result.sumHealth;
      healthModel.sumHealthState = getLevelByKey(result.sumHealthState);

      option.series[0].data[4].itemStyle.normal.color = getColorByKey(result.tmallState);
      option.series[0].data[3].itemStyle.normal.color = getColorByKey(result.scpayState);
      option.series[0].data[2].itemStyle.normal.color = getColorByKey(result.bankState);
      option.series[0].data[1].itemStyle.normal.color = getColorByKey(result.vcesState);
      option.series[0].data[0].itemStyle.normal.color = getColorByKey(result.lingxiState);
      option.series[0].data[4].name = '天猫旗舰店\n' + result.tmall + '%';
      option.series[0].data[3].name = '移动商城\n' + result.scpay + '%';
      option.series[0].data[2].name = '银行总对总\n' + result.bank + '%';
      option.series[0].data[1].name = '有价卡\n' + result.vces + '%';
      option.series[0].data[0].name = '灵犀语音\n' + result.lingxi + '%';

      chart.setOption(option);
    }

    function onSocket(option, chart) {
      socketServer.socket.on('health', function (resutlt) {
        try {
          initChart(option, chart, resutlt);
          $rootScope.$digest();
          //console.log('socket health...');
        } catch (e) {
          alert(e.name + ": " + e.message);
        }
      });
    }

    return {
      initHealthChart: function (id) {
        healthModel.loding = true;
        timeDataDisServer.queryHealth(function (result) {
          healthModel.loding = false;
          if ('10000' === result.state) {
            chart = echarts.init(document.getElementById(id));
            initChart(option, chart, result.data);
            onSocket(option, chart);
          }
        });
      }
    };
  }

  function timeDataDisServer(Restangular) {
    return {
      //实时数据展示：当日系统交易查询
      querySysTransaction: function (callback) {
        Restangular.one('sas/timeDataDis/sysTransaction/query').get().then(callback);
      },
      //实时数据展示：系统性能指数查询
      querySysPerformance: function (callback) {
        Restangular.one('sas/timeDataDis/sysPerformance/query').get().then(callback);
      },
      //实时数据展示：成功率(业务处理,系统处理)查询
      querySuccessRate: function (callback) {
        Restangular.one('sas/timeDataDis/successRate/query').get().then(callback);
      },
      //实时数据展示：健康度查询
      queryHealth: function (callback) {
        Restangular.one('sas/timeDataDis/health/query').get().then(callback);
      },
      //实时数据展示：分省实时交易成功率查询
      queryProvinceSuccessRateOfTrans: function (callback) {
        Restangular.one('sas/timeDataDis/provinceSuccessRateOfTrans/query').get().then(callback);
      },
      //实时数据展示：分省实时业务量查询
      queryProvinceVolumeOfBus: function (callback) {
        Restangular.one('sas/timeDataDis/provinceVolumeOfBus/query').get().then(callback);
      },
      //实时数据展示：实时业务量查询
      queryVolumeOfBus: function (callback) {
        Restangular.one('sas/timeDataDis/volumeOfBus/query').get().then(callback);
      },
      //实时数据展示：用户充值偏好查询
      queryTopUpPrefer: function (callback) {
        Restangular.one('sas/timeDataDis/topUpPrefer/query').get().then(callback);
      }
    };
  }
})();
